<template>
  <ex-dialog width="900px" class="ex-diolog" title="保险申请" :visible="visible" @closeDialog="handleClose">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="190px">
      <!-- <el-form-item label="审核状态:">
            <span>{{auditStatusDict}}</span>
          </el-form-item> -->
      <!-- <el-form-item label="保险规则配置:">
            <el-switch v-model="delivery" active-text="开" inactive-text="关" active-value="2" inactive-value="1"
              @change="switchChange" :disabled='switchDisabled'></el-switch>
          </el-form-item> -->
      <el-form-item label="保险类型：" prop="insType">
        <el-select v-model="ruleForm.insType" placeholder="请选择" style="width: 320px;">
          <el-option v-for="item in insTypeOptions" :key="item.id" :label="item.value" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="保险可划付比例:" prop="insRemitRatio" v-if="ruleForm.insType == '2'">
        <el-input v-model="ruleForm.insRemitRatio" placeholder="请输入" style="width: 320px;">
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="商户每月可申请划付比例:" prop="insApplyRemitRatio" v-if="ruleForm.insType == '2'">
        <el-input v-model="ruleForm.insApplyRemitRatio" placeholder="请输入" style="width: 320px;">
          <template slot="append">%</template>
        </el-input>
      </el-form-item>
      <el-form-item label="保额设置:" prop="total">
        <el-input v-model="ruleForm.total" placeholder="请输入" style="width: 320px;">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="保险期限设置:" required>
        <el-row>
          <el-col :span="10">
            <el-form-item prop="startTime">
              <el-date-picker type="date" placeholder="开始时间" :picker-options="star_Date" value-format="yyyy-MM-dd"
                v-model="ruleForm.startTime" style="width: 100%;" :disabled="startTimeDisabled" @blur="dateChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="1"><span style="display: flex;align-items: center;justify-content: center;">-</span></el-col>
          <el-col :span="10">
            <el-form-item prop="endTime">
              <el-date-picker type="date" placeholder="结束时间" :picker-options="end_Date" value-format="yyyy-MM-dd"
                v-model="ruleForm.endTime" style="width: 100%;"></el-date-picker>
            </el-form-item></el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="保险合约上传:" prop="insuranceContract" ref="insuranceContractRef">
        <el-upload class="upload-demo" :action="action" :on-preview="handlePreview" :on-remove="handleRemove"
          :before-remove="beforeRemove" :before-upload="beforeUpload" multiple :limit="1" :on-exceed="handleExceed"
          :file-list="fileList" :on-success="onSuccess">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="sumitOpen('ruleForm')" :loading="buttonLoding">确认提交</el-button>
        <el-button @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>

  </ex-dialog>
</template>
<script>
// components
import {
  adminDict,
  updateInsurance,
  addInsurance
} from "@/api/merchants";
import Loading from "@/components/Loading/index";
export default {
  components: {
    Loading,
  },
  props: {
    visible: Boolean,
    id: String,
    insuranceWalletId: {
      type: String,
      default: '',
    },
  },
  data() {
    var checkProportion = (rule, value, callback) => { //比例校验
      let regNumber = /^((?!0)\d{1,2}|100)$/; //1到100的正整数
      if (regNumber.test(value) == false) {
        return callback(new Error('请填写1到100的正整数'));
      } else {
        return callback()
      }
    };
    return {
      loading: false,
      buttonLoding: false, //保存loading
      action: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile",
      fileList: [],
      ruleForm: {
        merchantId: '', //商家id
        startTime: '', //保险期限开始时间 yyyy-MM-dd
        endTime: '', //保险期限结束时间 yyyy-MM-dd
        total: '', //保额设置
        insuranceContract: '', //保险合约
        insApplyRemitRatio: '',//商户每月可申请划付比例（申请划付使用） 单位百分比	
        insRemitRatio: '',//保险可划付比例（申请划付使用）单位百分比
        insType: '',//保险类型 1 自动划付 2 申请划付 merchant_ins_type
      },
      rules: { //表单校验规则
        total: [{
          required: true,
          message: '请输入保额数值',
          trigger: 'change'
        },],
        startTime: [{
          required: true,
          message: '请选择开始日期',
          trigger: 'change'
        }],
        endTime: [{
          required: true,
          message: '请选择结束日期',
          trigger: 'change'
        }],
        insuranceContract: [{
          required: true,
          message: '请上传合约',
          trigger: ['blur', 'change']
        }],
        insType: [{
          required: true,
          message: '请选择保险类型',
          trigger: ['blur', 'change']
        }],
        insRemitRatio: [{
          required: true,
          // message: '请输入保险可划付比例',
          validator: checkProportion,
          trigger: ['blur', 'change']
        }],
        insApplyRemitRatio: [{
          required: true,
          validator: checkProportion,
          // message: '请输入商户每月可申请划付比例',
          trigger: ['blur', 'change']
        }],
      },
      insTypeOptions: [],//保险类型
      end_Date: this.getendDate(), //限制活动结束时间选择
      star_Date: this.getstarDate(), //限制活动开始时间选择
      // isEdit: false, //是否是修改
      // editId: '', //修改id
      startTimeDisabled: false, //活动开始时间Disabled
      dialogVisible: false, //弹窗
      recordsVisible: false,//变更记录弹窗
      formInline: {
        merchantId: "", //商家id
        cardType: "", //卡类型 asset_card_type
        name: "", //卡名称
        status: "", //发售状态 asset_status
      },
    };
  },
  created() {
    // this.getDetail();
    this.getInsTypeOptions();
  },
  methods: {

    getInsTypeOptions() {
      //获取保险类型
      const params = {
        dictType: "merchant_ins_type",
      };
      adminDict(params).then((res) => {
        this.insTypeOptions = res.result[0].dictList;
      });
    },
    getstarDate() { //控制活动开始日期选择disable
      let that = this
      return {
        disabledDate(time) {
          console.log(that.ruleForm.startTime)
          return time.getTime() <= new Date() - 8.64e7;
        }
      }
    },
    getendDate() { //控制活动结束日期选择disable
      let that = this
      return {
        disabledDate(time) {
          if (that.ruleForm.endTime != '') {
            return time.getTime() <= new Date(that.ruleForm.endTime).getTime()
          } else {
            return time.getTime() <= new Date(that.ruleForm.startTime).getTime()
          }
        }
      }
    },
    dateChange() {
      this.ruleForm.endTime = ''
      console.log(this.ruleForm)
    },
    sumitOpen(formName) { //开启商家售卡保险功能保存\修改
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addInsuranceData()
          // if(this.insuranceWalletId){
          //   this.editInsuranceData()
          // }else{
          //   this.addInsuranceData()
          // }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 编辑保险配置
    editInsuranceData() {
      this.buttonLoding = true
      this.ruleForm.merchantId = this.id
      var data = {
        ...this.ruleForm,
        id: this.insuranceWalletId
      }
      updateInsurance(data).then((res) => {
        this.$message.success('保存成功');
        setTimeout(() => {
          this.buttonLoding = false
          this.handleClose()
          this.$emit('success')
        }, 1000)
      }).finally(() => {
        setTimeout(() => {
          this.buttonLoding = false;
        }, 1000);
      });
    },
    // 新增保险配置
    addInsuranceData() {
      this.buttonLoding = true
      this.ruleForm.merchantId = this.id
      var data = {
        ...this.ruleForm
      }
      addInsurance(data).then((res) => {
        this.$message.success('保存成功');
        setTimeout(() => {
          this.buttonLoding = false
          this.handleClose()
          this.$emit('success')
        }, 1000)
      }).finally(() => {
        setTimeout(() => {
          this.buttonLoding = false;
        }, 1000);
      });
    },
    // 上传
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.ruleForm.insuranceContract = ''
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      console.log(55556456, file.status)
      if (file && file.status === "success") {
        //删除
        return this.$confirm(`确定移除 ${file.name}？`);
      }
      // return this.$confirm(`确定移除 ${ file.name }？`);
    },
    beforeUpload(file) {
      console.log(file.type, file.name)
      this.fileName = file.name
      const isPDF = file.type === 'application/pdf';
      if (!isPDF) {
        this.$message.error('上传文件只能是 pdf 格式!');
      }
      return isPDF;
    },
    onSuccess(file) {
      console.log(file, '成功')
      this.ruleForm.insuranceContract = file.result.url
      this.$refs['insuranceContractRef'].clearValidate();
    },
    // end
    handleClose() {
      this.$emit("update:visible", false);
    },
  },
};
</script>
<style lang="scss" scoped>
.buttom {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 150px;
  margin-top: 30px;
}

.txt {
  font-size: 15px;
  margin-bottom: 20px;
}

.refuseMain {
  ::v-deep .el-radio-group {
    display: flex !important;
    flex-direction: column !important;
  }

  .el-radio {
    margin-bottom: 15px !important;
    margin-left: 20px !important;
  }

  .el-input--medium {
    font-size: 14px;
    margin-left: 44px;
  }

  .el-textarea {
    width: 90%;
  }
}

.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
  }

  .main {
    margin: 0 auto;
  }

  .pic-list {
    display: flex;
    justify-content: space-around;
    width: 660px;
  }

  .img {
    display: block;
    width: 200px;
    height: auto;
  }
}

.table_title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  margin-top: 20px;
}

.table_box {
  border: 1px solid #dfe6ec;
}

.table_detail {
  height: 44px;
  display: flex;
  font-size: 15px;
  border-bottom: 1px solid #dfe6ec;
}

.table_detail_l {
  border-right: 1px solid #dfe6ec;
  width: 30%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.table_detail_r {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.img_list {
  display: flex;
  margin: 20px 0 40px;
}

.img_list_box {
  margin-right: 10px;
}
</style>
